package framework.service.client;

import java.io.IOException;

import framework.Trait;
import framework.server.ServerException;
import framework.service.MessageService;
import framework.service.client.ClientRequest;
import framework.utils.http.Http;
import framework.utils.http.HttpResponse;

/**
 * Client response.<br>
 * <br>
 * If no one {@link ClientService} accept the message {@link ClientService#process(ClientMessage)} returns 
 * error message to the client<br>
 *
 * @author	Orlin Tomov
 * @version	0.2
 *
 */
public class ClientResponse extends MessageService implements ClientService {

	/**
	 * Create Client service
	 *
	 * @param container
	 * @param serviceName
	 */
	public ClientResponse(Trait container, String serviceName) {
		super(container, serviceName);
	}

	/** do nothing */
	@Override
	public void init() throws ServerException {
	}

	/**
	 * This is the last target of the sequential message {@link ClientMessage} 
	 * passed by all {@link ClientService#process(ClientMessage)} via {@link ClientManager#nextClient(ClientMessage)}.<br> 
	 * Because this means that the {@link ClientRequest} is not accepted by any of 
	 * the {@link ClientService}s the response is error
	 * 
	 * @param message contains ClientRequest
	 */
	@Override
	public void process(ClientMessage message) {
		ClientRequest clientRequest = message.getClientRequest();
		try {
			HttpResponse response = new HttpResponse(Http.Forbiden);
			response.addContent(response(), "text/html");
			response.print(clientRequest.getOutputStream());
			clientRequest.close();
			/**/log.info("Client disconnected.");
		} catch (IOException exception) {
			if (!clientRequest.isConnected()) {
				/**/log.error("Problem client comunication: ", exception);
			}
		}
	}

	/**
	 * Response to unknown client
	 *
	 * @return html page "403 Forbiden"
	 */
	private String response() {
		String result = "";
		result += "<html>\n";
		result += "<head>\n";
		result += "<title>403 Forbiden</title>\n";
		result += "</head>\n";
		result += "<body>\n";
		result += "<h1>Forbiden</h1>\n";
		result += "Execute access forbiden on this server.\n";
		result += "</body>\n";
		result += "</html>\n";
		return result;
	}
}
